package com.lemi.common.exception;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @author kevin
 * @since 2020/7/3 2:41 PM
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object handleIOException(NullPointerException e) {
        log.error(e.getMessage(), e);

        return errorMessage(e);
    }

    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object handleException(Exception e){
        log.error(e.getMessage(), e);
        return errorMessage(e);
    }

    /**
     * 用户Toen失效错误
     * @param e
     * @return
     */
    @ExceptionHandler(UserTokenException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object tokenException(Exception e){
        log.error(e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("code", "40102");
        map.put("msg", "登录已过期，请重新登录");
        return JSON.toJSON(map);
    }


    private Object errorMessage(Exception e){
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("code", "4003");
        map.put("msg", "系统错误，请联系管理员");
//        map.put("message ", DEFAULT_ERROR_VIEW);
        return JSON.toJSON(map);
    }
}
